package com.project.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionLis implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session创建");

        //得到session会话对象
        HttpSession session = se.getSession();
        //得到上下文对象
        ServletContext context = session.getServletContext();
        //从上下文对象中取出在线人数
        int num = (Integer) context.getAttribute("online");
        //重写绑定在线人数
        context.setAttribute("online",num+1);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session 销毁");

        ServletContext context = se.getSession().getServletContext();
        int num = (Integer) context.getAttribute("online");
        context.setAttribute("online",num-1);
    }
}
